// 全局变量
let refreshInterval;
let isAutoRefresh = true;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardData();
    startAutoRefresh();
});

// 加载仪表板数据
async function loadDashboardData() {
    try {
        const response = await fetch('/api/online-users');
        const users = await response.json();
        
        if (response.ok) {
            updateDashboardStats(users);
            updateOnlineUsersList(users);
        } else {
            console.error('加载数据失败:', users.error);
            showError('加载数据失败: ' + users.error);
        }
    } catch (error) {
        console.error('网络错误:', error);
        showError('网络连接错误，请检查服务器状态');
    }
}

// 更新仪表板统计信息
function updateDashboardStats(users) {
    const onlineCount = users.length;
    let totalReceived = 0;
    let totalSent = 0;
    let totalDuration = 0;
    
    users.forEach(user => {
        totalReceived += user.bytes_received || 0;
        totalSent += user.bytes_sent || 0;
        
        // 计算在线时长（秒）
        if (user.connected_since) {
            try {
                const connectedTime = new Date(user.connected_since);
                const now = new Date();
                const duration = Math.floor((now - connectedTime) / 1000);
                totalDuration += duration;
            } catch (e) {
                console.warn('无法解析连接时间:', user.connected_since);
            }
        }
    });
    
    // 更新统计显示
    document.getElementById('online-count').textContent = onlineCount;
    document.getElementById('total-traffic').textContent = formatBytes(totalReceived + totalSent);
    
    const avgDuration = onlineCount > 0 ? Math.floor(totalDuration / onlineCount / 60) : 0;
    document.getElementById('avg-duration').textContent = avgDuration + '分钟';
}

// 更新在线用户列表
function updateOnlineUsersList(users) {
    const container = document.getElementById('online-users-list');
    
    if (users.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-users-slash"></i>
                <h3>暂无在线用户</h3>
                <p>当前没有用户连接到OpenVPN服务器</p>
            </div>
        `;
        return;
    }
    
    const usersHTML = users.map(user => createUserCard(user)).join('');
    container.innerHTML = usersHTML;
}

// 创建用户卡片
function createUserCard(user) {
    const connectedTime = user.connected_since ? new Date(user.connected_since).toLocaleString('zh-CN') : '未知';
    
    return `
        <div class="user-card" data-connected-since="${user.connected_since}">
            <div class="user-header">
                <div class="user-avatar">
                    ${user.username.charAt(0).toUpperCase()}
                </div>
                <div class="user-info">
                    <h4>${user.username}</h4>
                    <p>${user.virtual_address}</p>
                </div>
            </div>
            <div class="user-stats">
                <div class="stat-row">
                    <span class="stat-label">接收流量</span>
                    <span class="stat-value">${user.traffic_received}</span>
                </div>
                <div class="stat-row">
                    <span class="stat-label">发送流量</span>
                    <span class="stat-value">${user.traffic_sent}</span>
                </div>
                <div class="stat-row">
                    <span class="stat-label">在线时长</span>
                    <span class="stat-value duration-value">${user.duration}</span>
                </div>
                <div class="stat-row">
                    <span class="stat-label">连接开始时间</span>
                    <span class="stat-value">${connectedTime}</span>
                </div>
            </div>
        </div>
    `;
}

// 刷新数据
function refreshData() {
    loadDashboardData();
    
    // 添加刷新动画
    const refreshBtn = document.querySelector('.refresh-btn');
    const icon = refreshBtn.querySelector('i');
    icon.classList.add('fa-spin');
    
    setTimeout(() => {
        icon.classList.remove('fa-spin');
    }, 1000);
}

// 开始自动刷新
function startAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
    
    if (isAutoRefresh) {
        refreshInterval = setInterval(() => {
            loadDashboardData();
        }, 30000); // 30秒刷新一次
        
        // 添加实时更新在线时长的定时器
        setInterval(() => {
            updateDashboardDurations();
        }, 1000); // 每秒更新一次在线时长
    }
}

// 实时更新仪表板在线时长
function updateDashboardDurations() {
    const userCards = document.querySelectorAll('.user-card');
    
    userCards.forEach(card => {
        const durationElement = card.querySelector('.duration-value');
        const connectedSince = card.getAttribute('data-connected-since');
        
        if (durationElement && connectedSince) {
            try {
                const connectedTime = new Date(connectedSince);
                if (!isNaN(connectedTime.getTime())) {
                    const now = new Date();
                    const duration = now - connectedTime;
                    const totalSeconds = Math.floor(duration / 1000);
                    
                    // 格式化显示时长
                    const hours = Math.floor(totalSeconds / 3600);
                    const minutes = Math.floor((totalSeconds % 3600) / 60);
                    const seconds = totalSeconds % 60;
                    
                    let durationStr;
                    if (hours > 0) {
                        durationStr = `${hours}小时${minutes}分钟${seconds}秒`;
                    } else if (minutes > 0) {
                        durationStr = `${minutes}分钟${seconds}秒`;
                    } else {
                        durationStr = `${seconds}秒`;
                    }
                    
                    durationElement.textContent = durationStr;
                }
            } catch (e) {
                console.warn('更新仪表板在线时长失败:', e);
            }
        }
    });
}

// 停止自动刷新
function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
    }
}

// 格式化字节数
function formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示错误信息
function showError(message) {
    const container = document.getElementById('online-users-list');
    container.innerHTML = `
        <div class="error-state">
            <i class="fas fa-exclamation-triangle"></i>
            <h3>加载失败</h3>
            <p>${message}</p>
            <button class="refresh-btn" onclick="refreshData()">
                <i class="fas fa-sync-alt"></i> 重试
            </button>
        </div>
    `;
}

// 页面卸载时清理定时器
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
});

// 页面可见性变化时处理自动刷新
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        stopAutoRefresh();
    } else {
        startAutoRefresh();
    }
}); 